package com.gzgy.ustore.api.dao.impl;

import com.gzgy.ustore.api.common.jdbc.StatementParameter;
import com.gzgy.ustore.api.dao.UserDao;
import com.gzgy.ustore.api.model.UserListModel;
import com.gzgy.ustore.api.model.UserModel;
import com.ustore.model.User;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class UserDaoImpl extends AbstractBaseDao<User> implements UserDao{
    @Override
    public UserModel loginWebPage(String userCode, String userPwd, String companyId) {

        //print sql
        StringBuffer sb = new StringBuffer();
        sb.append(" SELECT u.ID as userId, u.USER_NAME,o.ORG_NAME,ur.ROLE_ID FROM user u");
        sb.append(" LEFT JOIN organization o on o.ORG_ID = u.ORG_ID AND o.IS_DELETED = 0");
        sb.append(" INNER JOIN user_role ur on ur.USER_ID = u.id and ur.is_deleted=0 ");
        sb.append("  WHERE u.USER_CODE=? AND u.USER_PWD=? AND u.COMPANY_ID =?  AND u.IS_DELETED = 0; ");

        StatementParameter parameter = new StatementParameter();
        parameter.setString(userCode);
        parameter.setString(userPwd);
        parameter.setString(companyId);

        return this.query(sb.toString(),UserModel.class,parameter);
    }

    @Override
    public Integer userCount(String companyId) {
        String sql = "SELECT COUNT(ID) FROM USER WHERE COMPANY_ID =? AND IS_DELETED = 0";
        StatementParameter parameter = new StatementParameter();
        parameter.setString(companyId);
        return this.queryForInt(sql,parameter);
    }

    @Override
    public Integer userCount(String companyId, String userCode) {
        String sql = "SELECT COUNT(ID) FROM USER WHERE COMPANY_ID =? AND USER_CODE=? AND IS_DELETED = 0";
        StatementParameter parameter = new StatementParameter();
        parameter.setString(companyId);
        parameter.setString(userCode);
        return this.queryForInt(sql,parameter);
    }

    @Override
    public List<UserListModel> getUserList(String companyId,int index,int page) {
        StringBuffer sb = new StringBuffer();
        sb.append(" SELECT u.id,u.ORG_ID,u.user_Code,u.USER_NAME,o.ORG_NAME,u.EMAIL,U.PHONE,IFNULL(u.updated_by,u.CREATED_BY) as lastModifyUser,");
        sb.append(" IFNULL(u.UPDATED_TIME,u.CREATED_TIME) as lastModifyTime ,ur.ROLe_ID FROM `user` u");
        sb.append(" INNER JOIN user_role ur on ur.USER_ID =u.ID and ur.IS_DELETED =0 ");
        sb.append(" INNER JOIN organization o on o.org_id = u.org_id and o.IS_DELETED=0 ");
        sb.append(" where u.company_id= ? and u.is_deleted=0 limit ?,?");

        StatementParameter parameter  = new StatementParameter();
        parameter.setString(companyId);
        parameter.setInt(index*page);
        parameter.setInt(page);
        return this.queryForList(sb.toString(),UserListModel.class,parameter);
    }
}
